package algebra.rewriting.transform;

import algebra.op.AlgebraicOP;
import algebra.op.JoinOP;
import algebra.rewriting.RewriteRule;

public class AssociativeIntersectionS extends RewriteRule {

	private final AlgebraicOP op;

	public AssociativeIntersectionS(AlgebraicOP op) {
		this.op = op;
	}

	@Override
	public AlgebraicOP rewrite() {
		JoinOP ip = (JoinOP) op;
		JoinOP rp = ip.getSecondSubQuery().asIntersectionOP();
		AlgebraicOP lp = ip.getFirstSubQuery();
		return new JoinOP(new JoinOP(lp, rp.getFirstSubQuery()),
				rp.getSecondSubQuery());
	}

	@Override
	public boolean applicable() {
		if (this.op instanceof JoinOP) {
			JoinOP ip = op.asIntersectionOP();
			if (ip.getSecondSubQuery() instanceof JoinOP) {
				return true;
			}
		}
		return false;
	}

}
